<?php


namespace XinYaTable\Forms\Providers;

use Illuminate\Foundation\Support\Providers\RouteServiceProvider;
use Illuminate\Support\Facades\Route;

class FormServiceProvider extends RouteServiceProvider {
    /**
     * 根据表单的那个字段获取表单信息条目
     * @var string
     */
    public static $formTableIdentityColumn = 'id';
    
    /**
     * api前缀
     * @var string
     */
    protected $_routePrefix = '/api/admin/';
    
    /**
     * 是否使用dingo
     * @var bool
     */
    protected $_isDingo = false;
    
    /**
     * 路由文件路径
     * @var null
     */
    protected $_routePath = null;
    
    /**
     * 额外中间件
     * @var array
     */
    protected $_otherMiddlewareList = [];
    
    /**
     * dingo配置版本
     * @var string
     */
    protected $_versionOfDingo = 'v1';
    
    /**
     * 控制器命名空间,不可改变
     * @var string
     */
    private $_namespace = 'XinYaTable\Forms\Controllers';
    
    /**
     * @var string
     */
    protected $_module = 'Forms';
    
    /**
     * 结果处理中间件
     * @var string
     */
    public static $formAfterMiddlewareList = [\XinYaTable\Forms\Middleware\After::class];
    
    public function boot() {
        parent::boot();
    }
    
    public function map() {
        $this->_isDingo ? $this->_dingoRoute() : $this->_normalRoute();
    }
    
    public function register() {
        parent::register();
    }
    
    /**
     * 获取路由文件位置
     * @return null|string
     */
    protected function _getRoutePath() {
        $routePath = dirname(__DIR__) . DIRECTORY_SEPARATOR . ($this->_isDingo ? 'dingo_routes.php' : 'routes.php');
        
        return $this->_routePath ? $this->_routePath : $routePath;
    }
    
    /**
     * 获取路由前缀
     * @return string
     */
    protected function _getRoutePrefix() {
        return $this->_routePrefix . mb_strtolower($this->_module);
    }
    
    /**
     * 获取中间件
     * @return array
     */
    protected function _getMiddleware() {
        return array_merge($this->_otherMiddlewareList, static::$formAfterMiddlewareList);
    }
    
    /**
     * laravel默认路由设置
     */
    protected function _normalRoute() {
        Route::prefix($this->_getRoutePrefix())
            ->middleware($this->_getMiddleware())
            ->namespace($this->_namespace)
            ->group($this->_getRoutePath());
    }
    
    /**
     * dingo路由设置
     */
    protected function _dingoRoute() {
        $namespace  = $this->_namespace;
        $version    = $this->_versionOfDingo;
        $prefix     = $this->_getRoutePrefix();
        $middleware = $this->_getMiddleware();
        require $this->_getRoutePath();
    }
}